﻿using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour {

    [HideInInspector] public Collider Src;

    float Speed = 15.0f;
	Transform Trnsfrm;
    Vector3 Vel;
	void Awake () {
	    Trnsfrm = transform;
        Vel = Trnsfrm.up *Speed;

         PlayerLayer = LayerMask.NameToLayer("Player");  
	}
	
	void Update () {
        var np =  Trnsfrm.position + Vel*Time.deltaTime;
        //if( Camera.main.WorldToScreenPoint(np).x < 0  )
        //    Destroy(gameObject);

        RaycastHit hit;
        if( Physics.Raycast( new Ray( Trnsfrm.position, Vel.normalized ), out hit , Speed*Time.deltaTime*2, -1 ) && hit.collider != Src) {

            if(hit.collider.attachedRigidbody != null) { 
                if( hit.collider.gameObject.layer == PlayerLayer)
                    hit.collider.GetComponent<Character>().shove( Vel*100.0f, hit.point);
                else 
                    hit.collider.attachedRigidbody.AddForceAtPosition( Vel*4.0f, hit.point);
            }
           // Debug.Log("bullet hit "+hit.collider.name + "  "+(hit.collider.rigidbody != null)+hit.collider.rigidbody );
            Destroy(gameObject);       
        } else 
            Trnsfrm.position = np;
	}
    int PlayerLayer;// = LayerMask.NameToLayer("Player");  

}
